using PetShop.Web.Controls;
using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Transactions;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using PetShop.Web.Entities;

namespace PetShop.Web
{
    public partial class OrderProcess : Page
    {

        protected StaticAddress statAddrBill;
        protected StaticAddress statAddrShip;
        protected NavBar header;
        protected OrderInfo myOrder;



        public int InsertOrder(OrderInfo order)
        {

            using (SqlCommand cmd = new SqlCommand())
            {



                String strSQL = "Declare @ID int;" +
                                "Declare @ERR int;" +
                                " INSERT INTO Orders VALUES(@UserId, @Date, @ShipAddress1, @ShipAddress2, " +
                                " @ShipCity, @ShipState, @ShipZip, @ShipCountry, @BillAddress1, @BillAddress2, " +
                                "@BillCity, @BillState, @BillZip, @BillCountry,  @Total, @BillFirstName, " +
                                " @BillLastName, @ShipFirstName, @ShipLastName, @CardNumber, @CardExpiration, " +
                                " @CardType);" +
                                " SELECT @ID=@@IDENTITY;" +
                                " SELECT @ERR=@@ERROR;";


                cmd.Parameters.AddWithValue("@UserId", order.UserId);
                cmd.Parameters.AddWithValue("@Date", order.Date);
                cmd.Parameters.AddWithValue("@ShipAddress1", order.ShippingAddress.Address1);
                cmd.Parameters.AddWithValue("@ShipAddress2", order.ShippingAddress.Address2);
                cmd.Parameters.AddWithValue("@ShipCity", order.ShippingAddress.City);
                cmd.Parameters.AddWithValue("@ShipState", order.ShippingAddress.City);
                cmd.Parameters.AddWithValue("@ShipZip", order.ShippingAddress.State);
                cmd.Parameters.AddWithValue("@ShipCountry", order.ShippingAddress.Zip);
                cmd.Parameters.AddWithValue("@BillAddress1", order.BillingAddress.Address1);
                cmd.Parameters.AddWithValue("@BillAddress2", order.BillingAddress.Address1);
                cmd.Parameters.AddWithValue("@BillCity", order.BillingAddress.City);
                cmd.Parameters.AddWithValue("@BillState", order.BillingAddress.State);
                cmd.Parameters.AddWithValue("@BillZip", order.BillingAddress.Zip);
                cmd.Parameters.AddWithValue("@BillCountry", order.BillingAddress.Country);
                cmd.Parameters.AddWithValue("@Total", order.OrderTotal);
                cmd.Parameters.AddWithValue("@BillFirstName", order.BillingAddress.FirstName);
                cmd.Parameters.AddWithValue("@BillLastName", order.BillingAddress.LastName);
                cmd.Parameters.AddWithValue("@ShipFirstName", order.ShippingAddress.FirstName);
                cmd.Parameters.AddWithValue("@ShipLastName", order.ShippingAddress.LastName);
                cmd.Parameters.AddWithValue("@CardNumber", order.CreditCard.CardNumber);
                cmd.Parameters.AddWithValue("@CardExpiration", order.CreditCard.CardExpiration);
                cmd.Parameters.AddWithValue("@CardType", order.CreditCard.CardType);



                int i = 0;
                foreach (LineItemInfo item in order.LineItems)
                {
                    strSQL = strSQL + "INSERT INTO LineItem VALUES  ( " + " @ID" + ", @LineNumber" + i + ", @ItemId" +
                             i + ", @Quantity" + i + "); SELECT @ERR=@ERR+@@ERROR;";


                    cmd.Parameters.AddWithValue("@LineNumber" + i, item.Line);
                    cmd.Parameters.AddWithValue("@ItemId" + i, item.ItemId);
                    cmd.Parameters.AddWithValue("@Quantity" + i, item.Quantity);

                    i++;

                }


                int orderId = 0;
                using (
                    SqlConnection conn =
                        new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConnString"]))
                {





                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strSQL + "SELECT @ID, @ERR";


                    using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {


                        rdr.Read();

                        if (rdr.GetInt32(1) != 0)
                            throw new Exception("DATA INTEGRITY ERROR ON ORDER INSERT - ROLLBACK ISSUED");


                        orderId = rdr.GetInt32(0);
                    }

                    cmd.Parameters.Clear();
                }



                return orderId;
            }
        }





        private void InitializeComponent() { }




        private void TakeStock(InventoryItemInfo[] items)
        {



            using (SqlCommand cmd = new SqlCommand())
            {
                String strSql = null;

                int i = 0;


                foreach (InventoryItemInfo item in items)
                {
                    strSql = strSql + "UPDATE item SET InventoryQty = InventoryQty - ";
                    strSql = strSql + "@Quantity" + i + " WHERE ItemId = @ItemId" + i + ";";
                    cmd.Parameters.AddWithValue("@Quantity" + i, item.Quantity);
                    cmd.Parameters.AddWithValue("@ItemId" + i, item.ItemId);
                    i++;
                }

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSql;

                using (
                    SqlConnection conn =
                        new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConnString"]))
                {
                    cmd.Connection = conn;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }


        override protected void OnLoad(EventArgs e)
        {
            CartInfo cartInfo = (CartInfo)HttpContext.Current.Session["CART_KEY"];


            if ((cartInfo == null) || (cartInfo.Count == 0))
            {

                HttpContext.Current.Server.Transfer("ShoppingCart.aspx");
            }
            else
            {
                OrderInfo newOrder = new OrderInfo();
                newOrder.UserId = ((AccountInfo)HttpContext.Current.Session["ACCOUNT_KEY"]).UserId;
                newOrder.CreditCard = (CreditCardInfo)HttpContext.Current.Session["CREDITCARD_KEY"];
                newOrder.BillingAddress = (AddressInfo)HttpContext.Current.Session["BILLING_KEY"];
                newOrder.ShippingAddress = (AddressInfo)HttpContext.Current.Session["SHIPPING_KEY"];

                List<LineItemInfo> orderLineItems = new List<LineItemInfo>();

                int lineNum = 1;

                foreach (CartItemInfo item in cartInfo.Items)
                {

                    LineItemInfo lineItem1 = new LineItemInfo(item.ItemId, item.Name, lineNum, item.Quantity, item.Price);
                    orderLineItems.Add(lineItem1);
                    lineNum++;
                }
              
                newOrder.LineItems = orderLineItems.ToArray();

                newOrder.OrderTotal = cartInfo.Total;
                newOrder.Date = DateTime.Now;




                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
                {
                    int orderId = InsertOrder(newOrder);


                    List<InventoryItemInfo> inventoryItems = new List<InventoryItemInfo>();

                    foreach (LineItemInfo item in newOrder.LineItems)
                    {
                        InventoryItemInfo lineItem = new InventoryItemInfo(item.ItemId, item.Quantity);
                        inventoryItems.Add(lineItem);
                    }



                    TakeStock(inventoryItems.ToArray());

                    ts.Complete();

                    newOrder.OrderId = orderId;
                }




                HttpContext.Current.Session["CART_KEY"] = null;
                HttpContext.Current.Session["CREDITCARD_KEY"] = null;
                HttpContext.Current.Session["BILLING_KEY"] = null;
                HttpContext.Current.Session["SHIPPING_KEY"] = null;




                lblOrderId.Text = newOrder.OrderId.ToString();
                lblOrderDate.Text = newOrder.Date.ToLongDateString();
                ;
                lblUserId.Text = newOrder.UserId;
                lblCardType.Text = newOrder.CreditCard.CardType;
                lblCardNumber.Text = newOrder.CreditCard.CardNumber;
                lblCardExpiration.Text = newOrder.CreditCard.CardExpiration;

                statAddrBill.address = newOrder.BillingAddress;
                statAddrShip.address = newOrder.ShippingAddress;

                cart.DataSource = newOrder.LineItems;
                cart.DataBind();

                lblOrderTotal.Text = newOrder.OrderTotal.ToString("c");
            }
        }
    }
}